package com.aiyige.page.publish.photo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.PhotoModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.PhotoModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectpublishinterest.SelectPublishInterestPage;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.inputintroduction.InputIntrodutionPage;
import com.aiyige.page.publish.photo.adapter.InterestAdapter;
import com.aiyige.page.publish.photo.adapter.PublishPhotoAdapter;
import com.aiyige.page.publish.photo.model.PhotoFormModel;
import com.aiyige.page.publish.photo.model.PublishPhotoItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeEnterInputFilter;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.UUIDUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.misc.TransactionManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Track("发布图集")
@Route(path = ARouterConfig.PublishPhotoPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishPhotoPage extends BaseActivity {
    public static final int REQUEST_CODE_SELECT_PHOTO = 1;
    public static final int REQUEST_CODE_SELECT_INTEREST = 2;
    public static final int REQUEST_CODE_INPUT_COURSE_INTRODUCTION = 10;
    public static final int MAX_TITLE_INPUT_NUM = 30;

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.inputNumTv)
    TextView inputNumTv;
    @BindView(R.id.maxInputNumTv)
    TextView maxInputNumTv;
    @BindView(R.id.interestLayout)
    LinearLayout interestLayout;
    @BindView(R.id.locationLayout)
    LinearLayout locationLayout;
    @BindView(R.id.photoRv)
    RecyclerView photoRv;
    @BindView(R.id.addPhotoBtn)
    TextView addPhotoBtn;
    @BindView(R.id.locationTv)
    TextView locationTv;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleEtDeleteBtn)
    View titleEtDeleteBtn;
    PublishPhotoAdapter publishPhotoAdapter;
    LocationData locationData = new LocationData();
    BroadcastReceiver receiver;
    InputNumFilter inputNumFilter;
    TrackEvent trackEvent = new TrackEvent();
    CommonBottomDialogFragment locationOptionDialog;
    @BindView(R.id.interestRv)
    RecyclerView interestRv;
    InterestAdapter interestAdapter;
    @Autowired
    PhotoFormModel formModel = null;
    @BindView(R.id.introductionTv)
    TextView introductionTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_photo);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            ToastX.show(R.string.unknown_error);
            super.finish();
            return;
        }
        inputNumFilter = new InputNumFilter(MAX_TITLE_INPUT_NUM, false);
        maxInputNumTv.setText(String.valueOf(MAX_TITLE_INPUT_NUM));
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                inputNumTv.setText(String.valueOf(num));
            }
        });
        titleEt.setFilters(new InputFilter[]{new ExcludeEnterInputFilter(), new ExcludeEmojiInputFilter(), inputNumFilter});
        titleEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTitle(s.toString());
            }
        });
        titleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());

        titleTv.setText(R.string.publish_photo_title);
        titleActionBtn.setText(R.string.publish);
        photoRv.setLayoutManager(new LinearLayoutManager(this));
        publishPhotoAdapter = new PublishPhotoAdapter();
        publishPhotoAdapter.addFooterView(LayoutInflater.from(this).inflate(R.layout.publish_photo_page_recyclerview_footer, (ViewGroup) photoRv.getParent(), false));
        publishPhotoAdapter.bindToRecyclerView(photoRv);
        publishPhotoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        publishPhotoAdapter.remove(position);
                        autoConfigAddButton();
                        break;
                }
            }
        });

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH:
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                            if (locationData.isSuccess()) {
                                formModel.setLocationData(locationData);
                                locationTv.setText(formModel.getLocationData().getCity());
                            } else {
                                throw new Exception("定位失败");
                            }
                            break;
                    }
                } catch (Exception e) {
                    locationTv.setText(R.string.click_retry);
                    LocationUtil.showLocationFailedDialog(PublishPhotoPage.this);
                }
            }
        };
        containerLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = containerLayout.getRootView().getHeight() - containerLayout.getHeight();
                if (heightDiff > UIHelper.dip2px(PublishPhotoPage.this, 200)) { // if more than 200 dp, it's probably a keyboard...
                    addPhotoBtn.setVisibility(View.INVISIBLE);
                } else {
                    autoConfigAddButton();
                }
            }
        });
        interestRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        interestAdapter = new InterestAdapter();
        interestAdapter.bindToRecyclerView(interestRv);
        interestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    interestAdapter.remove(position);
                } catch (Exception e) {
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        registerReceiver(receiver, intentFilter);
        LocationService.startLocation(this);
        locationOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.location_option_dialog)
                .viewIdList(Arrays.asList(R.id.deleteLocationBtn, R.id.relocationBtn, R.id.cancelBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteLocationBtn:
                                locationData = new LocationData();
                                locationTv.setText(R.string.address_label);
                                break;
                            case R.id.relocationBtn:
                                LocationService.startLocation(PublishPhotoPage.this, true);
                                break;
                            case R.id.cancelBtn:
                                break;
                        }
                    }
                })
                .build();
        autoConfigAddButton();
        doSelectPhoto();
        updateView();
        if (formModel.getLocationData().isSuccess()) {
            locationTv.setText(formModel.getLocationData().getCity());
        }
    }

    public void updateView() {
        publishPhotoAdapter.setNewData(formModel.getPublishPhotoItemList());
        interestAdapter.setNewData(formModel.getInterestList());
        titleEt.setText(formModel.getTitle());
        if (ListUtil.isEmpty(interestAdapter.getData())) {
            interestRv.setVisibility(View.GONE);
        } else {
            interestRv.setVisibility(View.VISIBLE);
        }
        introductionTv.setText(formModel.getIntroduction());
    }

    @Override
    protected void onPause() {
        containerLayout.requestFocus();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void doSelectPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .minSelectNum(1)
                .maxSelectNum(PublishUtil.MAX_PUBLISH_PHOTO_NUM)
                .selectionMedia(getSelectedImage())
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(false)
                .enableCrop(false)
                .isCamera(true)
                .isGif(true)
                .compress(false)
                .imageSpanCount(4)
                .forResult(REQUEST_CODE_SELECT_PHOTO);
    }

    @OnClick({R.id.introductionLayout, R.id.titleEtDeleteBtn, R.id.titleBackBtn, R.id.titleActionBtn, R.id.interestLayout, R.id.locationLayout, R.id.addPhotoBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleEtDeleteBtn:
                titleEt.setText("");
                break;
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                doPublish();
                break;
            case R.id.interestLayout:
//                if (formModel.getInterestList().size() >= InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM) {
//                    ToastX.show(StringUtils.getString(R.string.reach_max_select_interest_num_warning, InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM));
//                    break;
//                }
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPublishInterestPage)
                        .withObject("selectedInterestList", formModel.getInterestList())
                        .withObject("publishIndustryList", formModel.getIndustryList())
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                break;
            case R.id.locationLayout:
                locationOptionDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.introductionLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.InputIntroductionPage)
                        .withString("text", formModel.getIntroduction())
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_INTRODUCTION);
                break;
            case R.id.addPhotoBtn:
                doSelectPhoto();
                break;
        }
    }

    public boolean checkFormValidate() {
//        if (!locationData.isSuccess()) {
//            ToastX.show(R.string.location_unfinished);
//            LocationService.startLocation(this);
//            return false;
//        }

//        if (ListUtil.isEmpty(tagAdapter.getData())) {
//            ToastX.show(R.string.please_select_tag);
//            return false;
//        }
        if (TextUtils.isEmpty(titleEt.getText().toString())) {
            ToastX.show(R.string.title_can_not_empty);
            return false;
        }

        if (ListUtil.isEmpty(formModel.getInterestList())) {
            ToastX.show(R.string.interest_can_not_empty);
            return false;
        }

        if (ListUtil.isEmpty(publishPhotoAdapter.getData())) {
            ToastX.show(R.string.photo_can_not_empty);
            return false;
        }
        return true;
    }

    public void doPublish() {
        if (!checkFormValidate()) {
            return;
        }
        new CheckSensitiveWordTask(formModel).execute();
    }

    public class CheckSensitiveWordTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        PhotoFormModel formModel;

        public CheckSensitiveWordTask(PhotoFormModel formModel) {
            this.formModel = formModel;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishPhotoPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().checkSensitiveWord(PublishUtil.convertPhotoFormModelToMoment(formModel)).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o == null) {
                executePublish();
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }


    public void executePublish() {
        if (!RxNetTool.isWifi(this) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createPublishBuilder(this)
                    .setPositiveButton(R.string.confirm_upload, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new AsyncTask<PhotoFormModel, Object, Object>() {
                                LoadingDialog loadingDialog;
                                PhotoFormModel photoFormModel;

                                @Override
                                protected void onPreExecute() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(PublishPhotoPage.this)
                                            .message(R.string.text_process)
                                            .show();
                                }

                                @Override
                                protected Object doInBackground(PhotoFormModel... params) {
                                    photoFormModel = params[0];
                                    try {
                                        return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                                            @Override
                                            public Object call() throws Exception {
                                                long releaseDate = System.currentTimeMillis();
                                                PhotoModel photoModel = PhotoModel.newBuilder()
                                                        .userId(AccountUtil.getCurrentUser().getId())
                                                        .interest(JSON.toJSONString(photoFormModel.getInterestList()))
                                                        .industry(JSON.toJSONString(photoFormModel.getIndustryList()))
                                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                        .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                                        .cover(JSON.toJSONString(photoFormModel.getPublishPhotoItemList()))
                                                        .id(UUIDUtil.generate())
                                                        .title(photoFormModel.getTitle())
                                                        .introduction(photoFormModel.getIntroduction())
                                                        .location(JSON.toJSONString(photoFormModel.getLocationData()))
                                                        .releaseDate(releaseDate)
                                                        .sellDate(releaseDate)
                                                        .photoNum(photoFormModel.getPublishPhotoItemList().size())
                                                        .build();
                                                PhotoModelDao.getDao().create(photoModel);
                                                List<PublishPhotoItem> publishPhotoItemList = photoFormModel.getPublishPhotoItemList();
                                                for (PublishPhotoItem publishPhotoItem : publishPhotoItemList) {
                                                    UploadFileDao.getDao().create(UploadFile.newBuilder()
                                                            .userId(AccountUtil.getCurrentUser().getId())
                                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                            .storeKey(PublishUtil.generatePhotoFileStoreKey(publishPhotoItem.getPhotoUrl()))
                                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                                            .parentId(photoModel.getId())
                                                            .parentType(PublishUtil.PARENT_TYPE_PHOTO)
                                                            .fileLocalUrl(publishPhotoItem.getPhotoUrl())
                                                            .description(publishPhotoItem.getIntroduction())
                                                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                                            .totalSize(FileUtil.getFileSize(publishPhotoItem.getPhotoUrl()))
                                                            .build());
                                                }
                                                {
                                                    Map<String, String> attrs = new HashMap<>();
                                                    attrs.put("photo_num", String.valueOf(photoFormModel.getPublishPhotoItemList().size()));
                                                    trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_PHOTO_NUM, TrackEvent.PUBLISH_PHOTO_NUM_LABEL, attrs);
                                                }
                                                return null;
                                            }
                                        });
                                    } catch (Exception e) {
                                        return e;
                                    }

                                }

                                @Override
                                protected void onPostExecute(Object o) {
                                    loadingDialog.dismiss();
                                    if (o instanceof Exception) {
                                        ToastX.show(R.string.operation_failed);
                                    } else {
                                        PublishUtil.startPublish();
                                        ToastX.show(R.string.publishing_photo);
                                        PublishPhotoPage.super.finish();
                                        PublishUtil.jumpToDMPage(PublishPhotoPage.this);
                                    }
                                }
                            }.execute(formModel);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            new AsyncTask<PhotoFormModel, Object, Object>() {
                LoadingDialog loadingDialog;
                PhotoFormModel photoFormModel;

                @Override
                protected void onPreExecute() {
                    loadingDialog = LoadingDialog.newBuilder()
                            .with(PublishPhotoPage.this)
                            .message(R.string.text_process)
                            .show();
                }

                @Override
                protected Object doInBackground(PhotoFormModel... params) {
                    photoFormModel = params[0];
                    try {
                        return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                long releaseDate = System.currentTimeMillis();
                                PhotoModel photoModel = PhotoModel.newBuilder()
                                        .userId(AccountUtil.getCurrentUser().getId())
                                        .interest(JSON.toJSONString(photoFormModel.getInterestList()))
                                        .industry(JSON.toJSONString(photoFormModel.getIndustryList()))
                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                        .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                        .cover(JSON.toJSONString(photoFormModel.getPublishPhotoItemList()))
                                        .id(UUIDUtil.generate())
                                        .title(photoFormModel.getTitle())
                                        .introduction(photoFormModel.getIntroduction())
                                        .location(JSON.toJSONString(photoFormModel.getLocationData()))
                                        .releaseDate(releaseDate)
                                        .sellDate(releaseDate)
                                        .photoNum(photoFormModel.getPublishPhotoItemList().size())
                                        .build();
                                PhotoModelDao.getDao().create(photoModel);
                                List<PublishPhotoItem> publishPhotoItemList = photoFormModel.getPublishPhotoItemList();
                                for (PublishPhotoItem publishPhotoItem : publishPhotoItemList) {
                                    UploadFileDao.getDao().create(UploadFile.newBuilder()
                                            .userId(AccountUtil.getCurrentUser().getId())
                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                            .storeKey(PublishUtil.generatePhotoFileStoreKey(publishPhotoItem.getPhotoUrl()))
                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                            .parentId(photoModel.getId())
                                            .parentType(PublishUtil.PARENT_TYPE_PHOTO)
                                            .fileLocalUrl(publishPhotoItem.getPhotoUrl())
                                            .description(publishPhotoItem.getIntroduction())
                                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                            .totalSize(FileUtil.getFileSize(publishPhotoItem.getPhotoUrl()))
                                            .build());
                                }
                                {
                                    Map<String, String> attrs = new HashMap<>();
                                    attrs.put("photo_num", String.valueOf(photoFormModel.getPublishPhotoItemList().size()));
                                    trackEvent.sendEvent(MyApp.getAppContext(), TrackEvent.PUBLISH_PHOTO_NUM, TrackEvent.PUBLISH_PHOTO_NUM_LABEL, attrs);
                                }
                                return null;
                            }
                        });
                    } catch (Exception e) {
                        return e;
                    }

                }

                @Override
                protected void onPostExecute(Object o) {
                    loadingDialog.dismiss();
                    if (o instanceof Exception) {
                        ToastX.show(R.string.operation_failed);
                    } else {
                        PublishUtil.startPublish();
                        ToastX.show(R.string.publishing_photo_wait_a_second);
                        PublishPhotoPage.super.finish();
                        PublishUtil.jumpToDMPage(PublishPhotoPage.this);
                    }
                }
            }.execute(formModel);
        }
    }

    public void autoConfigAddButton() {
        addPhotoBtn.setVisibility(publishPhotoAdapter.getData().size() < PublishUtil.MAX_PUBLISH_PHOTO_NUM ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT_INTEREST:
                if (resultCode == RESULT_OK) {
                    List<Interest> interestList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INTEREST_DATA);
                    List<Interest> industryList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INDUSTRY_DATA);
                    formModel.setInterestList(interestList);
                    formModel.setIndustryList(industryList);
                    updateView();
                }
                break;
            case REQUEST_CODE_SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    List<PublishPhotoItem> selectedPhotoItemList = new LinkedList<>();
                    for (LocalMedia item : selectList) {
                        selectedPhotoItemList.add(PublishPhotoItem.newBuilder()
                                .photoUrl(item.getPath())
                                .build());
                    }
                    mergeSelected(selectedPhotoItemList);
                    autoConfigAddButton();
                } else {
                    if (ListUtil.isEmpty(publishPhotoAdapter.getData())) {
                        super.finish();
                    }
                }
                break;
            case REQUEST_CODE_INPUT_COURSE_INTRODUCTION:
                if (resultCode == RESULT_OK) {
                    formModel.setIntroduction(data.getStringExtra(InputIntrodutionPage.EXTRA_KEY_INPUT_STRING));
                    introductionTv.setText(formModel.getIntroduction());
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public List<LocalMedia> getSelectedImage() {
        List<LocalMedia> localMediaList = new LinkedList<>();
        List<PublishPhotoItem> publishPhotoItemList = publishPhotoAdapter.getData();
        for (PublishPhotoItem item : publishPhotoItemList) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(item.getPhotoUrl());
            localMediaList.add(localMedia);
        }
        return localMediaList;
    }

    public void mergeSelected(List<PublishPhotoItem> selectedItemList) {
        List<PublishPhotoItem> currentPhotoItemList = publishPhotoAdapter.getData();
        Iterator<PublishPhotoItem> currentIterator = currentPhotoItemList.iterator();
        outerLoop:
        while (currentIterator.hasNext()) {
            PublishPhotoItem currentItem = currentIterator.next();
            Iterator<PublishPhotoItem> selectedIterator = selectedItemList.iterator();
            while (selectedIterator.hasNext()) {
                PublishPhotoItem selectedItem = selectedIterator.next();
                if (currentItem.getPhotoUrl().equals(selectedItem.getPhotoUrl())) {
                    selectedIterator.remove();
                    continue outerLoop;
                }
            }
            currentIterator.remove();
        }
        currentPhotoItemList.addAll(selectedItemList);
        publishPhotoAdapter.notifyDataSetChanged();
    }

    @Override
    public void finish() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PublishPhotoPage.super.finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }
}
